<template>

  <div class="app-container">

    <el-form  ref="form" :model="form" label-width="80px" v-loading="formLoading">

      <el-form-item label="名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="form.call_phone" placeholder="多个请用逗号隔开"></el-input>
      </el-form-item>
      <el-form-item label="介绍">
        <el-input :rows="5" type="textarea" v-model="form.introduce"></el-input>
      </el-form-item>
      <el-form-item label="营业时间">
        <el-time-select
          placeholder="起始时间"
          v-model="form.business_s_time"
          :picker-options="{
            start: '08:00',
            step: '01:00',
            end: '23:00'
          }">
        </el-time-select>
        <el-time-select
          placeholder="结束时间"
          v-model="form.business_e_time"
          :picker-options="{
            start: '08:00',
            step: '01:00',
            end: '23:00'
          }">
        </el-time-select>
      </el-form-item>

      <el-form-item label="照片">

        <el-upload
          action="/guard/upload?module=repairFactory"
          list-type="picture-card"
          :file-list="form.imgs"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>


      <el-form-item label="区域" >
        <el-cascader ref="area" placeholder="省市县"
         v-model="form.selectArea"
         :options="area"
         :props="{ expandTrigger: 'hover' ,value:'code',label:'name'}"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址">
        <el-input style="width: 200px" v-model="form.address" ></el-input>
        <el-button style="margin-left: 5px" type="primary" @click="getLocation" >定位</el-button>
      </el-form-item>

      <el-form-item>
        <el-select @change="markPointAtMap" v-model="selectAddress" placeholder="请选择地址">
          <el-option
            v-for="(item,index) in addressList"
            :key="index"
            :label="item.label"
            :value="index"
          >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.address }}</span>

          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="经纬度">
        <el-input style="width: 200px" v-model="form.lng" placeholder="经度" ></el-input>
        <el-input style="width: 200px;margin-left: 5px" v-model="form.lat"  placeholder="纬度" ></el-input>
      </el-form-item>

      <el-form-item>
        <div style="width: 1200px;height:400px;" id="container"></div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">立即创建</el-button>
<!--        <el-button>取消</el-button>-->
      </el-form-item>
    </el-form>



  </div>

</template>
<script>

import { myGet,myPost } from '@/utils/myRequest'


const urlLst = '/guard/repair/factory/index';
const urlAdd = '/guard/repair/factory/add';
const urlDetail = '/guard/repair/factory/detail';
const urlDel = '/guard/repair/factory/del';
const urlGetArea = '/guard/getArea';
export default {

  data() {
    return {
      map:null,
      markerLayer:null,
      repairFactory:null,
      geometries:[],
      addressList:[],
      selectAddress:"",
      area:[],
      dialogVisible:false,
      dialogImageUrl:'',
      formLoading:false,
      key:"DDJBZ-W6XW6-3VESU-EYQWU-4XZH7-OIFI7",
      currLng:"",
      currLat:"",
      form:{
        name:'',
        call_phone:'',
        selectArea:[],
        address:'',
        lng:'',
        lat:'',
        business_s_time:'08:00',
        business_e_time:'23:00',
        introduce:"",
        imgs:[]
      },
    }
  },
  methods: {

    getCurrentLocation(){
      const url = "https://apis.map.qq.com/ws/location/v1/ip"
      this.$jsonp(url,{key:this.key, output: "jsonp"}).then(res => {
        this.currLng = res.result.location.lng
        this.currLat = res.result.location.lat
        this.initMap(this.currLat,this.currLng,)
      }).catch(err => {
        console.log(err)
      })

    },

    markPointAtMap(){

      const info = this.addressList[this.selectAddress]
      console.log("markPointAtMap",info)

      this.form.lat = info.lat
      this.form.lng = info.lng

      var center = new TMap.LatLng(info.lat,info.lng)
      this.map.setCenter(center)
      this.markerLayer.add([{
        "id": Math.random(),   //点标记唯一标识，后续如果有删除、修改位置等操作，都需要此id
        "styleId": 'myStyle',  //指定样式id
        "position": new TMap.LatLng(info.lat,info.lng),  //点标记坐标位置
      }])
    },

    getLocation(){
      const url = "https://apis.map.qq.com/ws/place/v1/search"
      const keyword = this.form.address
      let cityName = this.$refs.area.getCheckedNodes()[0].pathLabels

      if(cityName.length<=0 || typeof(cityName)=="undefined"){
        this.$message.error("请先选中城市！")
        return
      }
      cityName = cityName[cityName.length-1]

      const boundary="region("+cityName+")"
      console.log("boundary",boundary)
      this.$jsonp(url, {
        key: this.key,
        boundary: boundary,
        keyword: keyword,
        output: "jsonp"
      }).then(res => {
        console.log(res)
        const list = res.data

        if(list.length>0){
          this.addressList = []
          list.forEach(item=>{

            this.addressList.push({
              label:item.title.substr(0,15),
              address:item.address.substr(0,15),
              value:item.id,
              lat:item.location.lat,
              lng:item.location.lng
            })
          })
          this.selectAddress = 0

          this.markPointAtMap()

        }else{
          this.$message.error("未搜到相关地址！")
        }
      }).catch(err => {
        console.log(err)
      })

    },

    initMap(lat=39.984120,lng=116.307484) {
      var center = new TMap.LatLng(lat,lng)
      this.map = new TMap.Map(document.getElementById('container'), {
        center: center,//设置地图中心点坐标
        zoom: 15.2,   //设置地图缩放级别
        //pitch: 43.5,  //设置俯仰角
        //rotation: 45    //设置地图旋转角度
      });

      this.markerLayer = new TMap.MultiMarker({
        map: this.map,  //指定地图容器
        //样式定义
        styles: {
          //创建一个styleId为"myStyle"的样式（styles的子属性名即为styleId）
          "myStyle": new TMap.MarkerStyle({
            "width": 25,  // 点标记样式宽度（像素）
            "height": 35, // 点标记样式高度（像素）
          })
        }
      });


    },

    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //this.formLoading = true;
          myPost(urlAdd,this.form).then(res=>{
            this.formLoading = false;
            if(res.status){
              this.dialogFormVisible = false
              Object.assign(this.form,this.$options.data().form)
              this.addressList = []
              this.$message.success(res.msg);
            }
          })
        } else {
          //this.$message.error('验证失败！');
          return false;
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.form.imgs.push({
        uid:file.uid,
        url:res.data.records.url,
        path:res.data.records.filePath
        //url:process.env.VUE_APP_HOST + res.data.records.filePath
        //url:res.data.records.filePath
      });
    },

    handleRemove(file, imgList) {
      const uid = file.uid
      const index = this.form.cover_urls.findIndex((item)=>{
        return item.uid == uid
      })
      this.form.cover_urls.splice(index,1)
    },

    getArea(){
      myGet(urlGetArea).then(res=>{
        if(res.status){
          this.area = res.data.records
        }
      })
    },

    getDetail(id){
      myGet(urlDetail,{id}).then(res=>{
        if(res.status){
          console.log(res.data.records)
          this.repairFactory = res.data.records
          Object.assign(this.form,this.repairFactory)
          this.form.selectArea = [this.repairFactory.prov_code,this.repairFactory.city_code,this.repairFactory.county_code]
        }
      })
    },

  },
  mounted() {
    this.getArea()
    /*const id = this.$route.params.id
    if(typeof(id) != "undefined"){
      this.getDetail(id)
    }*/

    this.getCurrentLocation()

  },
  beforeDestroy() {
    this.map.destroy()
  }

}
</script>

<style >
.el-input-group__append{
  background-color: #409EFF;
  color: #ffffff
}
</style>
